package com.totoro.rabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by Niki on 2018/3/29 14:41
 */
public class RabbitMQDemo {
    private static String host = "192.168.22.111";
    private static int port = 5672;
    private static String userName = "guest";
    private static String password = "guest";

    private static final String QUEUE_NAME = "openimport:async_batch_org_queue";

    private static void addConsumer() {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);

        try {
            Connection connection = connectionFactory.newConnection();

            Channel channel = connection.createChannel();

            channel.queueDeclareNoWait(QUEUE_NAME, true, false, false, null);

            Consumer consumer = new DefaultConsumer(channel) {
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String msg = new String(body, "utf-8");
                    System.out.println(msg);
                    long deliveTag = envelope.getDeliveryTag();
                    //手动确认事务ack
                    getChannel().basicAck(deliveTag, false);
                }


            };

            channel.basicConsume(QUEUE_NAME, false, consumer);

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        addConsumer();
    }
}
